package com.heima.homeservicemanagementsystem.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.homeservicemanagementsystem.config.GiteeConstants;
import com.heima.homeservicemanagementsystem.entity.SysUser;
import com.heima.homeservicemanagementsystem.entity.bo.AccessToken;
import com.heima.homeservicemanagementsystem.entity.giteeInfo;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.GiteeLoginService;
import com.heima.homeservicemanagementsystem.service.SysUserService;
import com.heima.homeservicemanagementsystem.utils.RedisClient;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Description
 * @Author jcf
 * @Date 2025/3/9
 */
@Service
@AllArgsConstructor
public class GiteeLoginServiceImpl implements GiteeLoginService {
    private static final Logger log = LoggerFactory.getLogger(GiteeLoginServiceImpl.class);
    private final GiteeConstants giteeConstants;
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private RedisClient redisClient;

    @Override
    public String getAuth() {
        // 授权地址 ,进行Encode转码
        String authorizeURL = giteeConstants.getAuthorizeURL();

        // 回调地址 ,回调地址要进行Encode转码
        String redirectUri = giteeConstants.getRedirectURI();

        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 拼接url
        StringBuilder url = new StringBuilder();
        url.append(authorizeURL);
        url.append("?client_id=" + giteeConstants.getAppID());
        url.append("&response_type=code");
        // 转码
        url.append("&redirect_uri=" + redirectUri);
        url.append("&state=" + uuid);
        url.append("&scope=user_info");
        return url.toString();
    }

    @Override
    public Result getGitAccessToken(String code) {
        // 构造访问令牌的请求 URL
        StringBuilder url = new StringBuilder();
        url.append(giteeConstants.getAccessToken());
        url.append("?grant_type=authorization_code");
        url.append("&code=" + code);
        url.append("&client_id=" + giteeConstants.getAppID());
        url.append("&redirect_uri=" + giteeConstants.getRedirectURI());
        url.append("&client_secret=" + giteeConstants.getAppKEY());

        // 设置请求头，确保是以应用程序/x-www-form-urlencoded 格式发送请求
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 构造HttpEntity，包括请求头和请求体（如果需要发送数据）
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
//        System.out.println("dizhi "+url.toString());
        try {
            // 发送 POST 请求
            ResponseEntity<String> exchange = restTemplate.exchange(url.toString(), HttpMethod.POST, entity, String.class);

            ObjectMapper objectMapper = new ObjectMapper();
            AccessToken accessToken = objectMapper.readValue(exchange.getBody(), AccessToken.class);
//            redisClient.set(giteeConstants.getAccess_token(), accessToken.getAccess_token());
//            redisClient.set(giteeConstants.getRefresh_token(), accessToken.getRefresh_token());

            // 返回结果，假设认证成功
            return Result.success("认证成功", exchange.getBody());


        } catch (HttpClientErrorException e) {
            // 处理 401 Unauthorized 错误
            System.out.println("Error: " + e.getMessage());
            return Result.error("认证失败: " + e.getMessage());
        } catch (JsonMappingException e) {
            throw new RuntimeException(e);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public giteeInfo getGiteeUserInfo(String accessToken) throws JsonProcessingException {
        String url = giteeConstants.getUserInfo() + "?access_token=" + accessToken;


        // 发送 GET 请求
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        // 判断是否请求成功
//        if (exchange.getStatusCode().is2xxSuccessful()) {
//            return Result.success(exchange.getBody());
//        }
        //返回的是json数据
        String responseBody = exchange.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        giteeInfo giteeInfo = objectMapper.readValue(responseBody, giteeInfo.class);
        if (giteeInfo == null) {
            throw new RuntimeException("没有查询用户信息");
        }
        return giteeInfo;
        // 打印返回的响应体（用于调试）
//            System.out.println("姓名" + giteeInfo.getName());
//            SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getGiteeLogin, giteeInfo.getLogin()));
//            if (user == null) {
//                return Result.error("登录失败，请重新验证");
//            }else{
//                StpUtil.login(user.getId(),"pc");
//                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//                Map<String, String> map = new HashMap<>(2);
//                map.put("tokenHead", tokenInfo.tokenName);
//                map.put("token", tokenInfo.tokenValue);
//                return Result.success(map);
//            }


    }

    @Override
    public Result giteeLogin(giteeInfo giteeInfo) {
        SysUser user = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getGiteeLogin, giteeInfo.getLogin()));

        if (Objects.isNull(user)) {
            log.info("用户信息：{}", user);
            return Result.error("登录失败，请重新验证并查看是否绑定gitee");
        } else {
            StpUtil.login(user.getId(), "pc");
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            Map<String, String> map = new HashMap<>(2);
            map.put("tokenHead", tokenInfo.tokenName);
            map.put("token", tokenInfo.tokenValue);
            return Result.success(map);
        }
    }

    @Override
    public Result refashToken(String refresh_token) throws JsonProcessingException {
        log.info("用户的refresh_token：{}", refresh_token);
        String url = giteeConstants.getAccessToken() + "?grant_type=refresh_token&refresh_token=" + refresh_token;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 构造HttpEntity，包括请求头和请求体（如果需要发送数据）
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        AccessToken accessToken = objectMapper.readValue(exchange.getBody(), AccessToken.class);
//        redisClient.set(giteeConstants.getAccess_token(), accessToken.getAccess_token());
//        redisClient.set(giteeConstants.getRefresh_token(), accessToken.getRefresh_token());

        return Result.success("刷新成功", exchange);
    }
}
